<?php

namespace Modules\Queue\Library;

use Core\File;
use GuzzleHttp\Client;
use Modules\Queue\Models\Queue;
use Modules\File\Models\File as FileModel;

class ImagesToLocal
{
    public static $output = array();

    public static function to($body)
    {
        //$queue = new Queue();
        $newBody = preg_replace_callback("/<img.*?(src|SRC|href|HREF)=[\"|'| ]{0,}(http.*?\.(gif|jpg|jpeg|bmp|png))['|\"]{0,}.*?>/", 'self::imageRe', $body);
        //Queue::add('imgToLocal', serialize(self::$output));
        //$queue->add('imgToLocal',self::$output);
        $output = [
            'queue' => self::$output,
            'body' => $newBody
        ];
        self::$output = null;
        return $output;
    }

    public static function imageRe($matches)
    {
        //if (strtolower($matches[1]) == 'href') {
        //    return;
        //}
        $di = \Phalcon\Di::getDefault();
        $imgUrl = parse_url($matches[2]);
        $urlInfo = pathinfo($matches[2]);
        $httpHost = $di->getShared('request')->getHttpHost();
        if (!isset($urlInfo['extension']) || $imgUrl['host'] == $httpHost || !isset($urlInfo['filename'])) {
            return '';
        }
        $newFileName = md5($urlInfo['filename']);
        $fileDir = 'file/' . $urlInfo['extension'] . date('/Y/m/d/');
        $extension = $urlInfo['extension'];
        $filename = '/' . $fileDir . $newFileName . '.' . $extension;
        self::$output[] = [
            'url' => $matches[2],
            'dir' => $fileDir,
            'fileName' => $newFileName . '.' . $extension,
        ];
        return '<img src="' . $filename . '" />';
    }

    public static function imgToLocal(Queue $queue)
    {
        $queue->isRun();
        $data = objectToArray($queue->data);
        $httpClient = new Client();
        $total = count($data);
        $i = 1;
        foreach ($data as $key => $item) {
            $queue->percentage($i, $total);
            $i++;
            $fileModel = new FileModel();
            $fileModel->name = $item['fileName'];
            $fileModel->dir = $item['dir'];
            $fileModel->md5 = '';
            $fileModel->access = 20;
            if ($fileModel->save()) {
                File::mkDir(WEB_CODE . '/' . $item['dir']);
                $filePath = ROOT_DIR . WEB_CODE . '/' . $item['dir'] . $item['fileName'];

                //$handle = fopen($filePath, 'w');

                $response = $httpClient->get($item['url'], [
                    //'stream' => true,
                    'save_to' => $filePath,
                ]);
                //fclose($handle);

                if ($response->getStatusCode() == 200) {
                    unset($data[$key]);
                }
            }
        }
        if (empty($data)) {
            return true;
        }
        $queue->isRun(false);
        return $data;
    }
}
